<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--客户信息-->
			<view class="detail-item">
				<uni-section title="客户信息" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
					  <uni-forms-item label="客户姓名">
					    <view class="formRef-text main-flex">{{info.name}}</view>
					  </uni-forms-item>
						<uni-forms-item label="客户电话">
						  <view class="formRef-text main-flex">{{info.phone}}</view>
						</uni-forms-item>
						<uni-forms-item label="客户地址" name="addrId" required>
					    <uni-data-select
					    	v-model="formData.addrId"
					    	placeholder="请选择客户地址"
					    	:localdata="customerAddrList"></uni-data-select>
					  </uni-forms-item>
						<uni-forms-item label="订单备注" name="remark">
							<uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入订单备注"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
				</view>
				<uni-section title="商品清单" type="line"></uni-section>
				<view class="detail-content">
					<up-button
						class="add-btn main-flex"
						size="mini"
						type="primary"
						@click="openProduct">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">添加商品</view>
					</up-button>
					<view class="table">
						<ty-table
							:data="chooseProduct"
							:columns="columns"
							:sortable="true"
							:cellClassName="() => 'table-cell'"
							:headerCellClassName="() => 'table-cell'"
							stripe
							border>
							<template v-slot:left="{ row }">
								<view class="table-td-cell">
									<view class="table-td-row">
										名称：
										<text class="table-td-text">{{row.name}}</text>
									</view>
									<view class="table-td-row">
										单位：
										<text class="table-td-text">{{row.unit}}</text>
									</view>
								</view>
							</template>
							<template v-slot:center="{ row }">
								<view class="table-td-cell">
									<view class="table-td-row">
										规格标志：
										<uni-tag size="small" type="success" :text="row.moreSpec === 0 ? '单规格' : '多规格'" />
									</view>
									<view class="table-td-row">
										规格名称：
										<text class="table-td-text"></text>
									</view>
									<view class="table-td-row" v-if="checkPermi(['zhouyz:order:price'])">
										购买单价：
										<text class="table-td-text">{{row.purchasePrice}}</text>
									</view>
								</view>
							</template>
							<template v-slot:right="{ row }">
								<view class="table-td-cell">
									<view class="table-td-row">
										<uni-number-box @change="changeCount($event, row)" v-model="row.count" />
									</view>
									<view class="table-td-row">
										合计：
										<text class="table-td-text">{{totilProduct(row)}}</text>
									</view>
								</view>
							</template>
							<template v-slot:del="{ row }">
								<view class="table-td-cell">
									<uni-icons @click="delProduct(row)" type="trash-filled" color="#e43d33" size="30"></uni-icons>
								</view>
							</template>
							<template v-slot:empty>
								<view class="table-empty">
									<up-empty mode="data"/>
								</view>
							</template>
						</ty-table>
						<view class="totil">合计：￥{{totilAllProduct}}</view>
					</view>
				</view>
			</view>
			<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
		</view>
		<ty-product-picker
			@close="closeProduct"
			@change="changeProduct"
			:showProduct="showProduct"></ty-product-picker>
		<!--确认弹窗-->
		<up-popup :z-index="90" round="5" closeable :show="showMsg" @close="closeMsg" mode="center">
			<view class="msg">
				<view class="msg-header">消息</view>
				<view class="msg-content">
					<view class="msg-item" :class="`msg-item-${item.type}`" v-for="item in msgList" :key="item">{{item.content}}</view>
				</view>
				<view class="msg-footer main-flex">
					<up-button
						class="msg-footer-item"
						text="确认"
						type="primary"
						@click="closeMsg"></up-button>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import { timeFormat } from 'uview-plus'
import { customerAllAddr, customerInfo } from "@/api/erp_api/customer"
import { createOrder, addProduct } from "@/api/erp_api/order"
import { arrText } from '@/utils/ty.js';
import { Decimal } from 'decimal.js'
import { wholesalerList, examineFlagList, extendFlagList } from '@/utils/config.js';

	const userStore = useUserStore()
	const customerId = ref('')
	onLoad((option) => {
		if (option.customerId) {
			customerId.value = option.customerId
			getCustomerAddr()
			getDetail()
		}
	})
	
	// 获取地址
	const customerAddrList = ref([])
	const getCustomerAddr = () => {
		customerAllAddr({
			id: customerId.value
		}).then(res => {
			customerAddrList.value = res.data.map(item => {
				return {
					...item,
					value: item.id,
					text: item.detail
				}
			}) || []
		})
	}
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: customerId.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		customerInfo(params).then(res => {
			info.value = res.data || {}
			formData.value = {
				name: res.data.name
			}
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 商品选择
	const showProduct = ref(false)
	const columns = ref([
					{ title: '商品信息', key: 'left' },
					{ title: '价格单位', key: 'center' },
					{ title: '购买数量', key: 'right' },
					{ title: '操作', key: 'del', width: '40px' }]) 
	const chooseProduct = ref([])
	const openProduct = () => {
		showProduct.value = true
	}
	const closeProduct = () => {
		showProduct.value = false
	}
	const changeProduct = (e) => {
		const chooseProductId = chooseProduct.value.map(item => item.id)
		const productList = e.filter(item => chooseProductId.indexOf(item.id) === -1)
		chooseProduct.value = chooseProduct.value.concat(productList.map(item => {
			return {
				...item,
				count: ''
			}
		}))
	}
	// 删除
	const delProduct = (row) => {
		chooseProduct.value = chooseProduct.value.filter(item => item.id !== row.id)
	}
	const changeCount = (e, row) => {
		chooseProduct.value = chooseProduct.value.map(item => item.id === row.id ? {...item, count: e} : item)
	}
	const totilProduct = computed(() => {
		return (row) => {
			return row.count ? Decimal(row.count).mul(Decimal(row.sellPrice)).toString() : '0.00'
		}
	})
	const totilAllProduct = computed(() => {
		let money = '0.00'
		if (chooseProduct.value.length > 0) {
			money = chooseProduct.value.reduce((prev, cur, index, arr)=> {
				const oneMoney = cur.count ? Decimal(cur.count).mul(Decimal(cur.sellPrice)) : 0
				return Decimal(prev).add(oneMoney).toNumber()
			}, 0)
		}
		return money
	})
	
	// form表单数据
	const formData = ref({
		addrId: '',
		remark: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		addrId: {
			rules: [{ required: true, errorMessage: '请选择客户地址' }]
		}
	})
	const isSubmit = ref(false)
	const showMsg = ref(false)
	const msgList = ref([])
	// 提交
	const submit = () => {
		formRef.value.validate().then(async formRes => {
			if (chooseProduct.value.length === 0) {
				return modal.showToast(`请选择商品`)
			}
			const noFilter = chooseProduct.value.filter(item => !item.count)
			if (noFilter.length > 0) {
				return modal.showToast(`请填写${noFilter[0].name}的数量`)
			}
			const params = { ...formRes }
			isSubmit.value = true
			uni.showLoading({
				title: '订单创建中...',
				mask: true
			})
			const orderNo = await addOrder({
				...params,
				customerId: customerId.value
			})
			for(let i = 0; i < chooseProduct.value.length; i++) {
				const res = await addOrderProduct({
					orderNumber: orderNo,
					moreSpec: chooseProduct.value[i].moreSpec,
					payNumber: chooseProduct.value[i].count,
					productId: chooseProduct.value[i].id === 488 ? '' : chooseProduct.value[i].id,
					purchasePrice: chooseProduct.value[i].sellPrice
				})
				msgList.value.push({
					type: res.type,
					content: `商品：${chooseProduct.value[i].name} ${res.type === 1 ? '添加成功' : res.type === 2 ? '添加失败' : ''}`
				})
				if (i === chooseProduct.value.length - 1) { // 执行到最后一条
					uni.hideLoading()
					isSubmit.value = false
					showMsg.value = true
				}
			}
		})
	}
	
	// 创建订单
	const addOrder = (params) => {
		return new Promise((resovle, reject) => {
			createOrder(params).then(async (res) => {
				resovle(res.data)
			}).catch((err) => {
				isSubmit.value = false
				reject(err)
			})
		})
	}
	
	// 新增订单商品
	const addOrderProduct = (params) => {
		return new Promise((resovle, reject) => {
			addProduct(params).then(async (res) => {
				resovle({
					type: 1,
					content: res.msg
				})
			}).catch((err) => {
				resovle({
					type: 2,
					content: err
				})
			})
		})
	}
	const closeMsg = () => {
		showMsg.value = false
		msgList.value = []
		clear()
		uni.$emit('refreshList');  // 触发刷新事件
		uni.navigateBack({
			delta: 1
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			addrId: '',
			remark: ''
		}
	}
	
</script>

<style scoped lang="scss">
	
	.add-btn {
		width: 160rpx;
		margin: 0;
	}
	.table {
		margin-top: 10px;
	}
	.totil {
		margin-top: 10px;
		text-align: right;
		font-size: 16px;
		font-weight: 600;
	}
</style>
